<template>
  <div>
    <div class="layout-func-body" v-if="isShow">
      <div
        class="layout-cell"
        v-for="(item, idx) of layouts"
        :draggable="draggable"
        @dragstart="compoDragStart($event, item.layoutID)"
        :layoutID="item.layoutID"
        :title="$srv.getI18nByPath(item.detail)"
        :key="idx"
        @contextmenu.prevent="rightClick($event, idx)"
        @click="handleClick(idx)"
      >
        <!-- @dragstart="compoDragStart($event, `${idx}`)" -->
        <div
          class="layout-model"
          @mouseleave="mouseLeave"
          :id="activeKey === idx ? 'active' : ' '"
        >
          <o-layout-mini :config="item.layoutConfig"></o-layout-mini>
        </div>
        <!-- <span>{{ $srv.getI18nByPath(item.title) }}</span> -->
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import {
  T_srv,
  Tsrv,
  ifs,
  ts,
  tvs,
  vue,
  I_command,
  VtoolbarState
} from './config';

@T_srv.comp({})
export default class LayoutsPanel extends vue {
  @T_srv.prop() readonly isShow!: boolean;

  @T_srv.prop() readonly layoutID: string | number | undefined;

  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  @T_srv.prop({
    required: false,
    type: Boolean,
    default: false
  })
  draggable: boolean;

  /* 组件名 */
  private G_compName: string = 'LayoutsPanel';

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  // Setup.layout.list;
  private layouts: any = [];

  private layoutsb = Tsrv.utils.clone(this.layouts, true);

  private showMsgDropdown: boolean = false;

  private index: string = '';

  private configt: any = '';

  private num: number = 1;

  private keyto: number;

  private max: number = 0;

  private GT_command: I_command;

  // 选定单前的模板
  private currIdx: string = '';

  private openmenu: boolean = false;

  private activeKey: number = -1;

  private layoutused: { sysfunid: number; f_value: number; id: any }[] = [
    // {
    //   sysfunid: 0, // 布局表中_sys_fun_id 值同fun config里的layoutID
    //   f_value: 0 // 布局表中的模板是否已存在配置功能（次数）
    // }
  ];

  created() {
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;

    this.GT_command = this.GT_compBox.getCompMergeName(
      this.G_compID,
      'oSetupPanelCMD'
    );
    this.layoutInit();
  }

  destroyed() {
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);

    /* 最终应用组件销毁 */
    /* this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName,'funName'); */

    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }

    /* 如果是动态组件可能会关闭全局compBox */
    // this.GT_compBox = null
  }

  mounted() {
    this.G_compName = this.G_compName;
    this.$emit('compBoxInfo', this.GT_compBoxInfo);
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
  }

  public layoutDoChange(index: string) {
    this.layouts.forEach((el: any) => {
      if (el.layoutID === index) {
        this.$emit('on-layout-change', el.layoutConfig);
      }
    });
  }

  /**
   * init 初始从数据库中抓数据clr
   */
  public layoutInit() {
    this.max = 0;
    const gpd = new ts.T_getPartDataArg();
    gpd.setFunName('_sys_layout').setLang('zh-CN');
    gpd.setPage(1, 100).setDbType('mysql');
    gpd.setGlobalSearch('');
    gpd.setFilter({});
    gpd.setSort([
      {
        // field: '_sys_fun_id',
        field: 'f_number',
        value: tvs.V_sortValue.ASC
      } as ifs.I_sort
    ]);

    return new Promise((resolve, reject) => {
      Tsrv.getData<any, ifs.I_getPartDataArg>(gpd).then(
        ([b, res, rows, msg]) => {
          this.layouts = [];
          rows.forEach((el: any) => {
            el['fun_config'] = Tsrv.utils.toStringJSON(el.fun_config);
            // if (el._sys_fun_id > this.max) {
            if (el.f_number > this.max) {
              // this.max = el._sys_fun_id;
              this.max = el.f_number;
            }
            this.layouts.push(el.fun_config);
            this.layoutused.push({
              // sysfunid: el._sys_fun_id,
              sysfunid: el.f_number,
              f_value: el.f_value,
              id: el.id
            });
          });
          resolve(rows);
        }
      );
    });
  }

  public compoDragStart(e: any, idx: number) {
    e.dataTransfer.setData('layout_change', idx);
  }

  /**
   * @description: 布局被使用
   * @return {*}
   * @author: wiz
   * @Date: 2023-07-09 13:53:21
   * @LastEditors: clr
   * @LastEditTime: Do not edit
   */
  /**
   * name
   */
  public layoutUsed(val: any) {
    let isLayoutUsed = false;
    this.layoutused.forEach(el => {
      if (el.sysfunid === this.layouts[val].layoutID && el.f_value === 0) {
        isLayoutUsed = true;
      }
    });

    // if (this.layoutused.find(el => { return el.sysfunid == this.layouts[val].layoutID })) {
    //   isLayoutUsed = true;
    // }
    return isLayoutUsed;
  }

  public layoutIdvalued(val: any) {
    let isLayoutUsed = {};
    this.layoutused.forEach(el => {
      if (el.sysfunid === val) {
        isLayoutUsed = { sysfunid: el.sysfunid, f_value: el.f_value };
      }
    });

    return isLayoutUsed;
  }

  // eslint-disable-next-line consistent-return
  public handleToolDropClick(e: any, val: any) {
    // if (e === 'delmodel' && this.layoutUsed(val)) {
    if (e === 'delmodel') {
      if (val !== 0) {
        const sysfunid = this.layouts[val].layoutID;
        const TdelRec = new ts.T_ctdDelRec();
        const Tfilter = new ts.T_filter();
        TdelRec.setRule({} as ifs.I_rule).setFilter(
          // Tfilter.parseEQ('_sys_fun_id', sysfunid)
          Tfilter.parseEQ('f_number', sysfunid)
        );
        return new Promise((resolve, reject) => {
          Tsrv.delRows('_sys_layout', 'mysql', {} as ifs.I_rule, TdelRec).then(
            res => {
              const [b, r, _] = res;
              if (!b && _) {
                this.$msg(_);
              } else {
                this.layouts.splice(val, 1); // 删除模板
                this.layoutInit();
                resolve(r);
              }
            }
          );
        });
      }
    }
  }

  // eslint-disable-next-line consistent-return
  public delModel() {
    if (
      this.activeKey !== 0 &&
      this.activeKey > 0 &&
      this.layoutUsed(this.activeKey) // 模板表里的f_value必须大于0
    ) {
      const sysfunid = this.layouts[this.activeKey].layoutID;
      this.layouts.splice(this.activeKey, 1); // 删除模板
      const TdelRec = new ts.T_ctdDelRec();
      const Tfilter = new ts.T_filter();
      TdelRec.setRule({} as ifs.I_rule).setFilter(
        // Tfilter.parseEQ('_sys_fun_id', sysfunid)
        Tfilter.parseEQ('f_number', sysfunid)
      );
      return new Promise((resolve, reject) => {
        Tsrv.delRows('_sys_layout', 'mysql', {} as ifs.I_rule, TdelRec).then(
          res => {
            const [b, r, _] = res;
            this.layoutInit();
            resolve(r);
          }
        );
      });
    }
  }

  // 递归拆解layout
  private takeLayout(configp: any, n: number) {
    if (configp.type === 'layout') {
      this.takeLayout(configp.config.first, this.num);
      this.takeLayout(configp.config.second, this.num);
    } else {
      this.num = n + 1;
      configp.name = String(n);
    }
  }

  private arrayLength() {
    this.max = this.max + 1;
    return this.max;
  }

  private layoutisChang() {
    this.num = 1;
    this.takeLayout(this.layouts[this.keyto].layoutConfig, this.num);
    const originalnum = this.num;
    this.num = 1;
    this.takeLayout(this.layoutsb[this.keyto].layoutConfig, this.num);
    const newnum = this.num;
    if (originalnum !== newnum) {
      return false;
    }
    return true;
  }

  private arrayAdd(configx: {}) {
    this.layouts.push(configx);
    this.layouts[this.keyto] = this.layoutsb[this.keyto]; // 从克隆的还原
  }

  public rightClick(e, index: string) {
    if (!this.openmenu) {
      const list = [{ name: 'delmodel', title: '删除模板' }];
      this.GT_command.setGlobalContextMenuList(...list);
      this.GT_command.openGcontextMenu(this.G_compName, {
        clientX: e.clientX,
        clientY: e.clientY
      });
      this.currIdx = index;
      this.openmenu = true;
    } else {
      this.GT_command.closeGcontextMenu();
      this.openmenu = false;
    }
  }

  public onContextSelect(e) {
    this.handleToolDropClick(e, this.currIdx);
    this.currIdx = '';
  }

  public closeContextMenu() {
    this.GT_command.closeGcontextMenu();
  }

  public mouseLeave() {
    this.closeContextMenu();
  }

  public handleClick(key) {
    this.activeKey = key;
    this.GT_command.setToolbarState({
      name: VtoolbarState.DELETE,
      state: false
    });
  }
}
</script>
<style scoped lang="scss">
.layout-func-body {
  display: flex;
  flex: 1;
  flex-direction: column;
  height: 100%;
  padding-top: 10px;
  overflow-x: hidden;
  overflow-y: auto;
  .layout-cell {
    height: 100px;
    display: flex;
    margin: 10px 0;
    flex-direction: column;
    position: relative;
    #active {
      //被选中的样式
      border: 2px solid #987;
    }

    .layout-model {
      cursor: pointer;
      margin: 0 30px;
      flex-grow: 1;
      z-index: 2;
      pointer-events: none;
      border-radius: 5px;
      overflow: hidden;
      .layout-model-foot {
        float: left;
      }
    }
    span {
      text-align: center;
      line-height: 30px;
      z-index: 2;
    }
    .ivu-icon {
      position: absolute;
      left: 20px;
      z-index: 10;
      bottom: 8px;
      font-size: 18px;
      color: var(--default-hover-font-color);
    }
  }
}
</style>
